import React, { useRef, useState, useEffect, useCallback } from 'react';
import { Canvas, useThree, useFrame } from '@react-three/fiber';
import { OrbitControls, TransformControls, Grid, Html } from '@react-three/drei';
import * as THREE from 'three';
import AxesHelper from './AxesHelper';
import GridHelper from './GridHelper';

// 基本形状组件
const Box3D = ({ position, color, size, onSelect, selected }) => {
    const mesh = useRef();

    useEffect(() => {
        if (selected && mesh.current) {
            mesh.current.material.emissive.set('#555555');
        } else if (mesh.current) {
            mesh.current.material.emissive.set('#000000');
        }
    }, [selected]);

    return (
        <mesh
            ref={mesh}
            position={[position.x, position.y, position.z]}
            onClick={(e) => {
                e.stopPropagation();
                onSelect();
            }}
        >
            <boxGeometry args={[size.width, size.height, size.depth]} />
            <meshStandardMaterial color={color} />
        </mesh>
    );
};

const Sphere3D = ({ position, color, radius, onSelect, selected }) => {
    const mesh = useRef();

    useEffect(() => {
        if (selected && mesh.current) {
            mesh.current.material.emissive.set('#555555');
        } else if (mesh.current) {
            mesh.current.material.emissive.set('#000000');
        }
    }, [selected]);

    return (
        <mesh
            ref={mesh}
            position={[position.x, position.y, position.z]}
            onClick={(e) => {
                e.stopPropagation();
                onSelect();
            }}
        >
            <sphereGeometry args={[radius, 32, 32]} />
            <meshStandardMaterial color={color} />
        </mesh>
    );
};

// 场景组件
const ModelScene = ({
    objects,
    selectedObject,
    setSelectedObject,
    previewObject,
    setPreviewObject,
    onObjectPlaced,
    onObjectRemoved,
    showHelpers = true,
    transformMode,
    externalModels = []
}) => {
    const { camera, scene, raycaster, mouse, gl } = useThree();
    const planeRef = useRef();
    const mousePos = useRef(new THREE.Vector3());
    const meshRefs = useRef({});
    const externalModelRefs = useRef({});

    // 场景初始化
    useEffect(() => {
        camera.position.set(5, 5, 5);
        camera.lookAt(0, 0, 0);
    }, [camera]);

    // 射线投射处理，用于确定鼠标在3D空间中的位置
    const handleMouseMove = (event) => {
        if (!previewObject) return;

        // 计算鼠标在场景中的位置
        const rect = gl.domElement.getBoundingClientRect();
        mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
        mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;

        raycaster.setFromCamera(mouse, camera);

        // 与平面相交以获取3D空间中的点
        const intersects = raycaster.intersectObject(planeRef.current);
        if (intersects.length > 0) {
            mousePos.current.copy(intersects[0].point);
        }
    };

    // 单击左键放置对象
    const handleLeftClick = (event) => {
        if (event.button === 0 && previewObject) {
            // 将预览对象固定到当前位置
            const newObject = {
                ...previewObject,
                position: {
                    x: mousePos.current.x,
                    y: mousePos.current.y,
                    z: mousePos.current.z
                }
            };

            onObjectPlaced(newObject);
            setPreviewObject(null);
            event.stopPropagation();
        }
    };

    // 单击右键删除预览对象
    const handleRightClick = (event) => {
        if (event.button === 2 && previewObject) {
            setPreviewObject(null);
            event.preventDefault();
            event.stopPropagation();
        }
    };

    // 双击对象转为预览状态
    const handleDoubleClick = (event, object, index) => {
        setPreviewObject({ ...object });
        onObjectRemoved(index);
        event.stopPropagation();
    };

    // 添加事件监听
    useEffect(() => {
        const domElement = gl.domElement;

        const mouseMoveHandler = (event) => handleMouseMove(event);
        const mouseClickHandler = (event) => handleLeftClick(event);
        const contextMenuHandler = (event) => handleRightClick(event);

        domElement.addEventListener('mousemove', mouseMoveHandler);
        domElement.addEventListener('mousedown', mouseClickHandler);
        domElement.addEventListener('contextmenu', contextMenuHandler);

        return () => {
            domElement.removeEventListener('mousemove', mouseMoveHandler);
            domElement.removeEventListener('mousedown', mouseClickHandler);
            domElement.removeEventListener('contextmenu', contextMenuHandler);
        };
    }, [gl, previewObject, onObjectPlaced, setPreviewObject]);

    // 每帧更新预览对象的位置
    useFrame(() => {
        if (previewObject) {
            const previewMesh = scene.getObjectByName('preview');
            if (previewMesh) {
                previewMesh.position.copy(mousePos.current);
            }
        }
    });

    // 更新对象位置 - 使用useCallback减少不必要的重新创建
    const handleTransformChange = useCallback(() => {
        if (selectedObject !== null && meshRefs.current[`mesh-${selectedObject}`]) {
            const mesh = meshRefs.current[`mesh-${selectedObject}`];
            if (!mesh) return;

            const newPosition = {
                x: mesh.position.x,
                y: mesh.position.y,
                z: mesh.position.z
            };

            const newRotation = {
                x: mesh.rotation.x,
                y: mesh.rotation.y,
                z: mesh.rotation.z
            };

            const newScale = {
                x: mesh.scale.x,
                y: mesh.scale.y,
                z: mesh.scale.z
            };

            // 检查位置或旋转是否发生了变化
            const obj = objects[selectedObject];
            const positionChanged = obj && (
                obj.position.x !== newPosition.x ||
                obj.position.y !== newPosition.y ||
                obj.position.z !== newPosition.z
            );

            const rotationChanged = obj && obj.rotation && (
                obj.rotation.x !== newRotation.x ||
                obj.rotation.y !== newRotation.y ||
                obj.rotation.z !== newRotation.z
            );

            const scaleChanged = obj && obj.scale && (
                obj.scale.x !== newScale.x ||
                obj.scale.y !== newScale.y ||
                obj.scale.z !== newScale.z
            );

            // 如果位置、旋转或缩放发生了变化，则更新对象
            if (positionChanged || rotationChanged || scaleChanged) {
                const newObjects = [...objects];
                newObjects[selectedObject] = {
                    ...newObjects[selectedObject],
                    position: newPosition,
                    rotation: newRotation,
                    scale: newScale || { x: 1, y: 1, z: 1 }
                };

                // 如果是外部模型，同时更新externalModels中的数据
                if (obj.type === 'external_model' && obj.externalId) {
                    // 通知父组件更新外部模型数据
                    onObjectPlaced(newObjects[selectedObject], selectedObject);
                } else {
                    onObjectPlaced(newObjects[selectedObject], selectedObject);
                }
            }
        }
    }, [selectedObject, objects, onObjectPlaced]);

    return (
        <>
            {/* 增强光照效果 */}
            <ambientLight intensity={0.6} />
            <directionalLight
                position={[10, 10, 5]}
                intensity={1}
                castShadow
                shadow-mapSize-width={1024}
                shadow-mapSize-height={1024}
            />
            <directionalLight
                position={[-10, 5, -5]}
                intensity={0.5}
            />
            <hemisphereLight
                args={['#ffffff', '#303030', 0.3]}
            />

            {/* 辅助工具 - 可通过showHelpers属性控制显示/隐藏 */}
            {showHelpers && (
                <>
                    {/* 主网格平面 */}
                    <Grid
                        args={[20, 20]}
                        cellSize={1}
                        cellThickness={0.5}
                        cellColor="#6f6f6f"
                        sectionSize={5}
                        sectionThickness={1}
                        sectionColor="#9d4b4b"
                        fadeDistance={30}
                        fadeStrength={1.5}
                        followCamera={false}
                        infiniteGrid
                    />

                    {/* 添加三维坐标轴 */}
                    <AxesHelper
                        size={10}
                        labels={true}
                        labelSize={0.5}
                        labelOffset={0.2}
                    />
                </>
            )}

            {/* 改进的轨道控制器设置 */}
            <OrbitControls
                makeDefault
                enableDamping={true}
                dampingFactor={0.05}
                rotateSpeed={0.7}
                zoomSpeed={0.8}
                minDistance={1}
                maxDistance={30}
            />

            {/* 隐形平面用于射线相交检测 */}
            <mesh
                ref={planeRef}
                rotation={[-Math.PI / 2, 0, 0]}
                position={[0, 0, 0]}
                visible={false}
            >
                <planeGeometry args={[100, 100]} />
                <meshBasicMaterial transparent opacity={0} />
            </mesh>

            {/* 渲染所有场景中的对象 */}
            {objects.map((obj, index) => {
                const isSelected = selectedObject === index;
                const meshId = `mesh-${index}`;

                // 处理外部模型类型
                if (obj.type === 'external_model') {
                    // 查找对应的外部模型
                    const externalModel = externalModels.find(model => model.id === obj.externalId);
                    console.log(`渲染对象 ${index}:`, obj.type, `externalId:${obj.externalId}`, `找到模型:`, !!externalModel);

                    // 如果是从保存加载的模型，使用不同的视觉效果
                    if (obj.isFromSave || (obj.needsReimport && !externalModel)) {
                        // 使用更好的视觉表现渲染占位符
                        return (
                            <group
                                key={meshId}
                                ref={(el) => {
                                    if (el) {
                                        meshRefs.current[meshId] = el;
                                        el.position.set(obj.position.x, obj.position.y, obj.position.z);
                                        if (obj.rotation) {
                                            el.rotation.set(obj.rotation.x, obj.rotation.y, obj.rotation.z);
                                        }
                                        if (obj.scale) {
                                            el.scale.set(obj.scale.x, obj.scale.y, obj.scale.z);
                                        }
                                    }
                                }}
                                onClick={(e) => {
                                    e.stopPropagation();
                                    setSelectedObject(index);
                                }}
                            >
                                {/* 使用半透明立方体代表外部模型 */}
                                <mesh>
                                    <boxGeometry args={[1, 1, 1]} />
                                    <meshStandardMaterial
                                        color={obj.color || "#3366FF"}
                                        opacity={isSelected ? 0.9 : 0.7}
                                        transparent={true}
                                    />
                                </mesh>

                                {/* 添加边框线框以增强视觉效果 */}
                                <lineSegments>
                                    <edgesGeometry args={[new THREE.BoxGeometry(1.01, 1.01, 1.01)]} />
                                    <lineBasicMaterial color={isSelected ? "#FFFFFF" : obj.color || "#3366FF"} />
                                </lineSegments>

                                {/* 仅在选中状态下显示模型名称 */}
                                {isSelected && (
                                    <Html position={[0, 1.2, 0]} center>
                                        <div style={{
                                            color: 'white',
                                            background: 'rgba(0,0,255,0.7)',
                                            padding: '5px',
                                            borderRadius: '3px',
                                            fontSize: '12px',
                                            whiteSpace: 'nowrap'
                                        }}>
                                            {obj.fileName || '外部模型'}
                                            {obj.isFromSave ? ' (已保存)' : ''}
                                            {obj.needsReimport ? ' (需要重新导入)' : ''}
                                        </div>
                                    </Html>
                                )}
                            </group>
                        );
                    }

                    // 如果找不到对应的外部模型数据，显示警告
                    if (!externalModel || !externalModel.originalObject) {
                        console.warn(`未找到外部模型数据:`, obj.externalId);
                        return (
                            <group
                                key={meshId}
                                ref={(el) => {
                                    if (el) {
                                        meshRefs.current[meshId] = el;
                                        el.position.set(obj.position.x, obj.position.y, obj.position.z);
                                        if (obj.rotation) {
                                            el.rotation.set(obj.rotation.x, obj.rotation.y, obj.rotation.z);
                                        }
                                        if (obj.scale) {
                                            el.scale.set(obj.scale.x, obj.scale.y, obj.scale.z);
                                        }
                                    }
                                }}
                                onClick={(e) => {
                                    e.stopPropagation();
                                    setSelectedObject(index);
                                }}
                            >
                                <mesh>
                                    <boxGeometry args={[1, 1, 1]} />
                                    <meshStandardMaterial color="red" wireframe />
                                </mesh>
                                <Html position={[0, 1.5, 0]} center>
                                    <div style={{ color: 'red', background: 'rgba(0,0,0,0.7)', padding: '5px', borderRadius: '3px' }}>
                                        未找到模型数据
                                    </div>
                                </Html>
                            </group>
                        );
                    }

                    // 确保obj有scale属性
                    const scale = obj.scale || { x: 1, y: 1, z: 1 };
                    console.log(`渲染外部模型 ${index}，位置:`, obj.position, "旋转:", obj.rotation, "缩放:", scale, "颜色:", obj.color);

                    // 修改：使用唯一key确保在数组中的身份稳定
                    const stableKey = `external-${meshId}-${obj.externalId}`;

                    return (
                        <group
                            key={stableKey}
                            ref={(el) => {
                                if (el) {
                                    meshRefs.current[meshId] = el;

                                    // 确保应用位置、旋转和缩放
                                    el.position.set(obj.position.x, obj.position.y, obj.position.z);
                                    el.rotation.set(obj.rotation.x, obj.rotation.y, obj.rotation.z);
                                    el.scale.set(scale.x, scale.y, scale.z);
                                }
                            }}
                            onClick={(e) => {
                                e.stopPropagation();
                                setSelectedObject(index);
                            }}
                        >
                            {/* 用一个几何体标记模型中心点 */}
                            <mesh visible={isSelected} scale={[0.2, 0.2, 0.2]}>
                                <sphereGeometry args={[1, 16, 16]} />
                                <meshBasicMaterial color="#ff0000" wireframe />
                            </mesh>

                            {/* 自定义对象，用于渲染导入的模型 - 确保传递最新的模型数据 */}
                            <ExternalModel
                                modelData={{
                                    ...externalModel,
                                    color: obj.color // 确保颜色从objects数组传递
                                }}
                                isSelected={isSelected}
                            />
                        </group>
                    );
                }

                // 创建通用的属性对象
                const commonProps = {
                    key: meshId,
                    ref: (el) => (meshRefs.current[meshId] = el),
                    position: [obj.position.x, obj.position.y, obj.position.z],
                    rotation: obj.rotation ? [obj.rotation.x, obj.rotation.y, obj.rotation.z] : [0, 0, 0],
                    onClick: (e) => {
                        e.stopPropagation();
                        setSelectedObject(index);
                    },
                    onDoubleClick: (e) => handleDoubleClick(e, obj, index)
                };

                // 创建通用的材质属性
                const materialProps = {
                    color: obj.color,
                    emissive: isSelected ? '#555555' : '#000000'
                };

                switch (obj.type) {
                    case 'box':
                        return (
                            <mesh {...commonProps}>
                                <boxGeometry args={[obj.size.width, obj.size.height, obj.size.depth]} />
                                <meshStandardMaterial {...materialProps} />
                            </mesh>
                        );
                    case 'sphere':
                        return (
                            <mesh {...commonProps}>
                                <sphereGeometry args={[obj.radius, 32, 32]} />
                                <meshStandardMaterial {...materialProps} />
                            </mesh>
                        );
                    case 'cylinder':
                        return (
                            <mesh {...commonProps}>
                                <cylinderGeometry args={[obj.radius, obj.radius, obj.height, 32]} />
                                <meshStandardMaterial {...materialProps} />
                            </mesh>
                        );
                    case 'cone':
                        return (
                            <mesh {...commonProps}>
                                <coneGeometry args={[obj.radius, obj.height, 32]} />
                                <meshStandardMaterial {...materialProps} />
                            </mesh>
                        );
                    case 'torus':
                        return (
                            <mesh {...commonProps}>
                                <torusGeometry args={[obj.radius, obj.tube, 16, 100]} />
                                <meshStandardMaterial {...materialProps} />
                            </mesh>
                        );
                    case 'pyramid':
                        return (
                            <mesh {...commonProps}>
                                <coneGeometry
                                    args={[
                                        Math.max(obj.size.width, obj.size.depth) / 2,
                                        obj.size.height,
                                        4,
                                        1
                                    ]}
                                    rotation={[0, Math.PI / 4, 0]}
                                />
                                <meshStandardMaterial {...materialProps} />
                            </mesh>
                        );
                    default:
                        return null;
                }
            })}

            {/* 预览对象 */}
            {previewObject && (
                (() => {
                    switch (previewObject.type) {
                        case 'box':
                            return (
                                <mesh
                                    name="preview"
                                    position={[mousePos.current.x, mousePos.current.y, mousePos.current.z]}
                                    rotation={previewObject.rotation ? [previewObject.rotation.x, previewObject.rotation.y, previewObject.rotation.z] : [0, 0, 0]}
                                >
                                    <boxGeometry
                                        args={[
                                            previewObject.size.width,
                                            previewObject.size.height,
                                            previewObject.size.depth
                                        ]}
                                    />
                                    <meshStandardMaterial
                                        color={previewObject.color}
                                        transparent
                                        opacity={0.7}
                                    />
                                </mesh>
                            );
                        case 'sphere':
                            return (
                                <mesh
                                    name="preview"
                                    position={[mousePos.current.x, mousePos.current.y, mousePos.current.z]}
                                    rotation={previewObject.rotation ? [previewObject.rotation.x, previewObject.rotation.y, previewObject.rotation.z] : [0, 0, 0]}
                                >
                                    <sphereGeometry args={[previewObject.radius, 32, 32]} />
                                    <meshStandardMaterial
                                        color={previewObject.color}
                                        transparent
                                        opacity={0.7}
                                    />
                                </mesh>
                            );
                        case 'cylinder':
                            return (
                                <mesh
                                    name="preview"
                                    position={[mousePos.current.x, mousePos.current.y, mousePos.current.z]}
                                    rotation={previewObject.rotation ? [previewObject.rotation.x, previewObject.rotation.y, previewObject.rotation.z] : [0, 0, 0]}
                                >
                                    <cylinderGeometry args={[previewObject.radius, previewObject.radius, previewObject.height, 32]} />
                                    <meshStandardMaterial
                                        color={previewObject.color}
                                        transparent
                                        opacity={0.7}
                                    />
                                </mesh>
                            );
                        case 'cone':
                            return (
                                <mesh
                                    name="preview"
                                    position={[mousePos.current.x, mousePos.current.y, mousePos.current.z]}
                                    rotation={previewObject.rotation ? [previewObject.rotation.x, previewObject.rotation.y, previewObject.rotation.z] : [0, 0, 0]}
                                >
                                    <coneGeometry args={[previewObject.radius, previewObject.height, 32]} />
                                    <meshStandardMaterial
                                        color={previewObject.color}
                                        transparent
                                        opacity={0.7}
                                    />
                                </mesh>
                            );
                        case 'torus':
                            return (
                                <mesh
                                    name="preview"
                                    position={[mousePos.current.x, mousePos.current.y, mousePos.current.z]}
                                    rotation={previewObject.rotation ? [previewObject.rotation.x, previewObject.rotation.y, previewObject.rotation.z] : [0, 0, 0]}
                                >
                                    <torusGeometry args={[previewObject.radius, previewObject.tube, 16, 100]} />
                                    <meshStandardMaterial
                                        color={previewObject.color}
                                        transparent
                                        opacity={0.7}
                                    />
                                </mesh>
                            );
                        case 'pyramid':
                            return (
                                <mesh
                                    name="preview"
                                    position={[mousePos.current.x, mousePos.current.y, mousePos.current.z]}
                                    rotation={previewObject.rotation ? [previewObject.rotation.x, previewObject.rotation.y, previewObject.rotation.z] : [0, 0, 0]}
                                >
                                    {/* 使用特殊修改的BoxGeometry创建金字塔 */}
                                    <coneGeometry
                                        args={[
                                            Math.max(previewObject.size.width, previewObject.size.depth) / 2,
                                            previewObject.size.height,
                                            4,
                                            1
                                        ]}
                                        rotation={[0, Math.PI / 4, 0]}
                                    />
                                    <meshStandardMaterial
                                        color={previewObject.color}
                                        transparent
                                        opacity={0.7}
                                    />
                                </mesh>
                            );
                        default:
                            return null;
                    }
                })()
            )}

            {/* 变换控制器 */}
            {selectedObject !== null && meshRefs.current[`mesh-${selectedObject}`] && (
                <TransformControls
                    object={meshRefs.current[`mesh-${selectedObject}`]}
                    mode={transformMode}
                    onMouseUp={handleTransformChange}
                    onObjectChange={handleTransformChange}
                />
            )}
        </>
    );
};

// 外部模型组件
const ExternalModel = ({ modelData, isSelected }) => {
    const group = useRef();
    const { scene } = useThree();

    // 添加调试状态
    const [loaded, setLoaded] = useState(false);
    const [error, setError] = useState(null);

    // 添加唯一标识符进行跟踪
    const modelId = modelData?.id || 'unknown';

    // 记录模型最后的颜色，用于检测颜色变化
    const lastColorRef = useRef(modelData?.color);

    // 添加缓存对象的引用
    const clonedObjectRef = useRef(null);

    // 跟踪组件挂载状态
    const isMounted = useRef(true);

    // 组件挂载和卸载时的处理
    useEffect(() => {
        console.log(`[模型${modelId}] 组件挂载`);
        isMounted.current = true;

        return () => {
            console.log(`[模型${modelId}] 组件卸载`);
            isMounted.current = false;

            // 清理缓存的对象
            if (clonedObjectRef.current) {
                try {
                    clonedObjectRef.current.traverse(node => {
                        if (node.geometry) node.geometry.dispose();
                        if (node.material) {
                            if (Array.isArray(node.material)) {
                                node.material.forEach(material => material.dispose());
                            } else {
                                node.material.dispose();
                            }
                        }
                    });
                    clonedObjectRef.current = null;
                } catch (e) {
                    console.warn(`[模型${modelId}] 清理缓存对象失败:`, e);
                }
            }
        };
    }, [modelId]);

    // 检测模型颜色变化 - 分离处理颜色变化逻辑
    useEffect(() => {
        if (!clonedObjectRef.current || !modelData) return;

        const currentColor = modelData.color;

        // 只有当颜色真的变化时才更新
        if (currentColor && currentColor !== lastColorRef.current) {
            console.log(`[模型${modelId}] 颜色已变化: ${lastColorRef.current} -> ${currentColor}`);
            lastColorRef.current = currentColor;

            // 遍历模型，更新颜色
            clonedObjectRef.current.traverse((child) => {
                if (child.isMesh) {
                    if (child.material) {
                        // 如果已经有颜色，则更新
                        if (child.material.color) {
                            child.material.color.set(currentColor);
                        }

                        // 同时更新缓存的原始材质的颜色
                        if (child.userData.originalMaterial && child.userData.originalMaterial.color) {
                            child.userData.originalMaterial.color.set(currentColor);
                        }

                        // 更新高亮材质(如果存在)
                        if (child.userData.highlightMaterial && child.userData.highlightMaterial.color) {
                            // 为高亮效果设置稍微亮一点的颜色
                            const highlightColor = new THREE.Color(currentColor);
                            highlightColor.r = Math.min(1, highlightColor.r * 1.2);
                            highlightColor.g = Math.min(1, highlightColor.g * 1.2);
                            highlightColor.b = Math.min(1, highlightColor.b * 1.2);
                            child.userData.highlightMaterial.color.copy(highlightColor);
                        }
                    }
                }
            });
        }
    }, [modelData, modelId]);

    // 创建和删除模型 - 优化并使用useCallback以减少重渲染
    const createModel = useCallback(() => {
        // 如果没有原始模型数据，显示错误
        if (!modelData || !modelData.originalObject) {
            console.error(`[模型${modelId}] 模型数据不完整:`, modelData);
            setError("模型数据不完整");
            return;
        }

        try {
            console.log(`[模型${modelId}] 开始渲染`);

            // 如果已经有克隆对象，直接使用
            if (clonedObjectRef.current) {
                console.log(`[模型${modelId}] 使用已有的克隆对象`);
            } else {
                // 克隆原始对象
                clonedObjectRef.current = modelData.originalObject.clone();
                console.log(`[模型${modelId}] 创建新的克隆对象`);

                // 记录当前颜色
                lastColorRef.current = modelData.color;
            }

            const objectClone = clonedObjectRef.current;

            // 应用变换
            objectClone.position.set(0, 0, 0); // 组内位置归零，使用group的position进行定位
            objectClone.rotation.set(0, 0, 0); // 同上，使用group的rotation

            // 添加到场景中的组
            if (group.current) {
                // 清空组中现有内容
                while (group.current.children.length > 0) {
                    group.current.remove(group.current.children[0]);
                }

                // 添加新对象
                group.current.add(objectClone);

                // 遍历对象，设置材质和颜色
                objectClone.traverse((child) => {
                    if (child.isMesh) {
                        // 如果有材质，克隆保存原始材质
                        if (child.material) {
                            // 保存原始材质（如果还没有保存）
                            if (!child.userData.originalMaterial) {
                                child.userData.originalMaterial = child.material.clone();
                            }

                            // 设置材质颜色
                            if (child.material.color) {
                                child.material.color.set(modelData.color || '#ffffff');
                            }

                            // 确保材质可见
                            child.material.transparent = false;
                            child.material.opacity = 1.0;
                            child.material.side = THREE.DoubleSide; // 双面渲染

                            // 添加接收阴影和投射阴影的能力
                            child.castShadow = true;
                            child.receiveShadow = true;
                        } else {
                            // 如果没有材质，创建一个
                            child.material = new THREE.MeshStandardMaterial({
                                color: modelData.color || '#ffffff',
                                side: THREE.DoubleSide
                            });
                            child.userData.originalMaterial = child.material.clone();
                            child.castShadow = true;
                            child.receiveShadow = true;
                        }

                        // 确保网格可见
                        child.visible = true;
                    }
                });

                // 只在组件仍然挂载时设置状态
                if (isMounted.current) {
                    setLoaded(true);
                    setError(null);
                }
            }
        } catch (error) {
            console.error(`[模型${modelId}] 渲染失败:`, error);
            if (isMounted.current) {
                setError(error.message || "渲染失败");
            }
        }
    }, [modelData, modelId]);

    // 监听模型数据变化，创建或更新模型
    useEffect(() => {
        createModel();
    }, [createModel]);

    // 高亮选中的模型 - 优化性能，减少不必要的更新
    useEffect(() => {
        if (!group.current || !clonedObjectRef.current) return;

        // 应用高亮效果
        clonedObjectRef.current.traverse((child) => {
            if (child.isMesh && child.userData.originalMaterial) {
                if (isSelected) {
                    // 高亮显示选中的模型
                    if (!child.userData.highlightMaterial) {
                        // 创建高亮材质（如果还没有）
                        const material = child.userData.originalMaterial.clone();

                        // 设置发光效果
                        if (material.emissive) {
                            material.emissive.set('#444444');
                            material.emissiveIntensity = 0.5;
                        }

                        // 稍微调亮颜色
                        if (material.color) {
                            const color = material.color.clone();
                            color.r = Math.min(1, color.r * 1.2);
                            color.g = Math.min(1, color.g * 1.2);
                            color.b = Math.min(1, color.b * 1.2);
                            material.color = color;
                        }

                        child.userData.highlightMaterial = material;
                    }

                    // 应用高亮材质
                    child.material = child.userData.highlightMaterial;
                } else {
                    // 恢复原始材质
                    child.material = child.userData.originalMaterial;
                }
            }
        });
    }, [isSelected]);

    // 渲染
    return (
        <group ref={group} name={`model-${modelId}`}>
            {error && (
                <mesh position={[0, 0, 0]}>
                    <boxGeometry args={[1, 1, 1]} />
                    <meshStandardMaterial color="red" wireframe />
                    <Html position={[0, 1.5, 0]} center>
                        <div style={{ color: 'red', background: 'rgba(0,0,0,0.7)', padding: '5px', borderRadius: '3px' }}>
                            错误: {error}
                        </div>
                    </Html>
                </mesh>
            )}
            {!loaded && !error && (
                <mesh position={[0, 0, 0]}>
                    <sphereGeometry args={[0.5, 16, 16]} />
                    <meshStandardMaterial color="yellow" wireframe />
                    <Html position={[0, 1, 0]} center>
                        <div style={{ color: 'yellow', background: 'rgba(0,0,0,0.7)', padding: '5px', borderRadius: '3px' }}>
                            加载中...
                        </div>
                    </Html>
                </mesh>
            )}
        </group>
    );
};

// 主场景容器组件
const ThreeModelScene = ({
    objects,
    selectedObject,
    setSelectedObject,
    previewObject,
    setPreviewObject,
    onObjectPlaced,
    onObjectRemoved,
    showHelpers = true,
    transformMode,
    externalModels = []
}) => {
    const handleContextMenu = (e) => {
        e.preventDefault();
        if (previewObject) {
            setPreviewObject(null);
        }
    };

    // 添加调试日志，跟踪组件渲染和更新
    console.log('[ThreeModelScene] 渲染，对象数量:', objects.length,
        '外部模型数量:', externalModels.length,
        'externalModels IDs:', externalModels.map(m => m.id));

    // 外部模型详情
    if (objects.filter(obj => obj.type === 'external_model').length > 0) {
        console.log('[ThreeModelScene] 外部模型对象:',
            objects.filter(obj => obj.type === 'external_model').map(obj => ({
                id: obj.externalId,
                position: obj.position
            }))
        );
    }

    return (
        <div onContextMenu={handleContextMenu} style={{ width: '100%', height: '100%' }}>
            <Canvas>
                <ModelScene
                    objects={objects}
                    selectedObject={selectedObject}
                    setSelectedObject={setSelectedObject}
                    previewObject={previewObject}
                    setPreviewObject={setPreviewObject}
                    onObjectPlaced={onObjectPlaced}
                    onObjectRemoved={onObjectRemoved}
                    showHelpers={showHelpers}
                    transformMode={transformMode}
                    externalModels={externalModels}
                />
            </Canvas>
        </div>
    );
};

export default ThreeModelScene; 